package haupt.dev.Config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.pmw.tinylog.Logger;

public class ConfigFileReader implements ConfigReader {

	private String workingDirPath;
	private File configFile;
	private File configDir;
	private Properties properties;
	
	public ConfigFileReader() {
		try {
			setConfigFilePath();
	
			if(!configFile.exists()) {
				createConfigFile();
			}
			
			properties = new Properties();
			properties.load(new FileInputStream(configFile));
		} catch (FileNotFoundException e) {
			createConfigFile();
		} catch (IOException e) {
			Logger.info("IOException: Can't load config file. Shutdown...");
			System.exit(0);
		}
	}

	private void setConfigFilePath() {
		workingDirPath = System.getProperty("user.dir");
		configDir = new File(workingDirPath + File.separator + "config");
		configFile = new File(configDir.getPath() + File.separator + "config.ini");
	}

	private void createConfigFile() {
		try {
			if(!configDir.exists()) {
				configDir.mkdir();
			}
			FileOutputStream os;
			fillPropertiesWithDefaultData();
			configFile.createNewFile();
			os = new FileOutputStream(configFile);
			properties.store(os, "created file with default values");
			Logger.info("Config-File with default values created. Please edit the config file and restart the program.");
			os.close();
		} catch (IOException e) {
			Logger.info("IOException: Can't create config file with default values.");
		} finally {
			System.exit(0);
		}
	}
	
	private void fillPropertiesWithDefaultData() {
		properties = new Properties();
		properties.put("host", "localhost");
		properties.put("port", "3306");
		properties.put("database", "");
		properties.put("user", "root");
		properties.put("password", "");
		properties.put("gameAccount", "");
		properties.put("gamePassword", "");
		properties.put("server", "titan");
	}

	@Override
	public Properties getProperties() {
		return properties;
	}

	@Override
	public String getProperty(String key) {
		return properties.getProperty(key);
	}
}
